<template>
  <div class="container mb15">
    <div class="banner mt15">
      <img src="../../assets/images/setting-banner.png" alt="">
    </div>
    <div v-if="userInfo" class="wxkj-tab">
      <el-tabs v-model="tab">
        <el-tab-pane label="招聘者信息" name="0">
          <el-card class="box-card">
            <div class="wxkj-icon-title mb20">
              <span class="icon" />
              <span>招聘者信息</span>
            </div>
            <div class="content-center">
              <el-form ref="form" :model="form" label-width="80px" :rules="rules">
                <el-form-item label="头像：">
                  <el-upload
                    ref="logo"
                    class="uploader-item"
                    accept=".jpg,.png,.jpeg"
                    :action="$uploadUrl"
                    :data="{'biz':'public/user/' + new Date().getFullYear() + '/' + parseInt(new Date().getMonth() + 1)}"
                    :headers="{'X-Access-Token':token}"
                    :show-file-list="false"
                    :on-success="avatarUpload"
                    :before-upload="beforeAvatarUpload"
                    :limit="1"
                  >
                    <img v-if="avatar" :src="avatar" class="avatar">
                    <i v-else class="el-icon-plus uploader-item-icon" />
                  </el-upload>
                </el-form-item>
                <el-form-item label="姓名：" prop="name">
                  <el-input v-model="form.name" placeholder="请填写姓名" />
                </el-form-item>
                <el-form-item label="称呼：" prop="nickName">
                  <el-input v-model="form.nickName" placeholder="请填写称呼" />
                </el-form-item>
                <el-form-item label="职位：" prop="stationName">
                  <el-input v-model="form.stationName" placeholder="请填写职位" />
                </el-form-item>
                <el-form-item label="部门：" prop="sysOrgCode">
                  <el-input v-model="form.sysOrgCode" placeholder="请填写职位" />
                </el-form-item>
                <el-form-item label="手机：" prop="phone">
                  <el-input v-model="form.phone" placeholder="请填写手机" disabled readonly />
                </el-form-item>
                <el-form-item label="邮箱：" prop="email">
                  <el-input v-model="form.email" placeholder="请填写邮箱" />
                </el-form-item>
                <el-form-item class="tc">
                  <el-button type="primary" @click="submit">保存</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="同事管理" name="1">
          <el-card class="box-card">
            <div class="filter-container">
              <el-input v-model="listQuery.queryValue" placeholder="搜索同事姓名/手机/邮箱" clearable style="width: 240px;" class="mr20" />
              <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
            </div>
            <div class="filter-container">
              <el-button v-if="form.enRoleType == 1" type="primary" icon="el-icon-document-add" @click="editShow(null)">添加同事</el-button>
            </div>
            <el-table
              :key="tableKey"
              v-loading="listLoading"
              :data="list"
              fit
              stripe
              highlight-current-row
              style="width: 100%;"
            >
              <el-table-column label="姓名" align="center" width="200" prop="name">
                <template slot-scope="{row}">
                  {{ row.name }}
                  <el-tag
                    v-if="row.enRoleType == 1"
                    class="tag"
                    size="mini"
                    effect="plain"
                  >
                    超级管理员
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="手机号" align="center" prop="phone" />
              <el-table-column label="职位" align="center" prop="stationName" />
              <el-table-column label="邮箱" align="center" prop="email" />
              <el-table-column label="在线职位" align="center" prop="onlineJobCount" />
              <el-table-column label="近7天接收简历" align="center" prop="sevenCount" />
              <el-table-column label="操作" align="center" width="183">
                <template v-if="form.enRoleType == 1" slot-scope="{row}">
                  <el-button type="text" :disabled="row.enRoleType == 1" @click="editShow(row)">编辑</el-button>
                  <el-button type="text" :disabled="row.enRoleType == 1" @click="transfer(row.id)">转让管理员</el-button>
                  <el-button type="text" :disabled="row.enRoleType == 1" @click="del(row.userId)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              prev-text="上一页"
              next-text="下一页"
              layout="prev, pager, next, jumper"
              :page.sync="listQuery.pageNo"
              :limit.sync="listQuery.pageSize"
              @pagination="getList"
            />
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </div>
    <colleague-edit ref="colleagueEdit" @refresh="getList" />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import colleagueEdit from './components/colleagueEditDrawer'
import { mapGetters } from 'vuex'
import { list, del, edit, transRole } from '@/api/colleague'
export default {
  name: '',
  components: { Pagination, colleagueEdit },
  props: {},
  data() {
    var mobileValidate = (rule, value, callback) => {
      if (!(/^1\d{10}$/.test(value))) {
      	callback(new Error('请准确填写手机号'))
      }
      callback()
    }
    return {
      tab: 0,
      form: {
        id: '',
        name: '',
        nickName: '',
        stationName: '',
        sysOrgCode: '',
        phone: '',
        email: '',
        photoId: ''
      },
      avatar: '',
      rules: {
        name: [
          { required: true, message: '请填写姓名', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请填写手机', trigger: 'blur' },
          { validator: mobileValidate, message: '请填写正确的手机号', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请填写邮箱', trigger: 'blur' },
          { type: 'email', message: '请填写正确的邮箱', trigger: 'blur' }
        ]
      },
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 5,
        queryValue: ''
      }
    }
  },
  computed: {
    ...mapGetters([
      'companyInfo',
      'userInfo',
      'token'
    ])
  },
  watch: {
    userInfo: {
      deep: true,
      immediate: true,
      handler(e) {
        this.avatar = e && e.photoId_dictText
        this.form = e && JSON.parse(JSON.stringify(e))
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 招聘者信息
    this.getList()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 销毁
  destroyed() {},
  // 方法
  methods: {
    submit() {
      this.$refs.form.validate(pass => {
        const prams = JSON.parse(JSON.stringify(this.form))
        prams.createTime = ''
        prams.updateTime = ''
        if (pass) {
          edit(prams).then(response => {
            this.$message.success('修改成功！')
            this.$store.dispatch('user/getUserInfo')
          })
        }
      })
    },
    avatarUpload(res, file) {
      console.log(res)
      this.$refs['logo'].clearFiles()// 清空上传列表
      this.form.photoId = res.result.fileId
      this.avatar = res.result.url
    },
    beforeAvatarUpload(file) {
      const istu = file.type
      // const isLt2M = file.size / 1024 / 1024 < 2
      if (istu !== 'image/png' && istu !== 'image/jpeg') {
        this.$message.error('图片格式不正确!')
      }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!')
      // }
      return istu
      // return isJPG && isLt2M
    },
    editShow(item) {
      this.$refs.colleagueEdit.show(JSON.parse(JSON.stringify(item)))
    },
    getList() {
      this.listLoading = true
      const listQuery = JSON.parse(JSON.stringify(this.listQuery))
      if (listQuery.title) {

      }
      list(listQuery).then(res => {
        this.list = res.result.records
        this.listLoading = false
        this.total = res.result.total
      })
    },
    // 搜索
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 排序
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    // 删除同事
    del(id) {
      this.$confirm('确定要删除此同事信息吗。', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del({
          id: id
        }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      }).catch(() => {
      })
    },
    // 转让
    transfer(id) {
      this.$confirm('转让后，你将失去超级管理员的权限，对应的权限将移交给TA。', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        transRole({
          id: id
        }).then(res => {
          this.$message({
            type: 'success',
            message: '转让成功!'
          })
          this.afterTransfer()
        })
      }).catch(() => {
      })
    },
    async afterTransfer() {
      await this.$store.dispatch('user/getUserInfo')
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
.banner{
    width: 100%;
    height: 140px;
    img{
      width: 100%;
      height: 100%;
    }
  }
  .content-center{
    width: 500px; margin: 0 auto;
  }
  .tag{
    position: absolute;
    top: 5px;
    right: 0;
  }
  .content{padding: 0 20px;
    .explain{font-size:14px;font-weight:400;line-height:24px;color:#666666;margin-top: 12px; margin-bottom: 23px;}
  }
  .box-card{
    height: 650px;
  }
  ::v-deep .uploader-item{
    width: 100px;
    height: 100px;
  }
  ::v-deep .el-upload{
    width: 100px;
    height: 100px;
    border: 1px dashed #d9d9d9;
    cursor: pointer;
    position: relative;
    border-radius: 6px;
    background: none;
    .avatar{
      width: 98px;
      height: 98px;
    }
    .uploader-item-icon {
      display: block;
      font-size: 28px;
      color: #8c939d;
      width: 98px;
      height: 98px;
      line-height: 98px;
      text-align: center;
    }
  }
</style>
